import * as http from "http"
import * as fs from "fs"
import {IncomingMessage} from "http";

export enum CallBackStatus {
  progress,
  finish,
  error,
}


export function download(url: string, filePath: string, callback: (status: CallBackStatus, data?: any) => void) {
  // 1.创建文件
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath)
  }
  fs.writeFileSync(filePath, null as any)
  const file = fs.createWriteStream(filePath)


  // 2.下载文件
  const req = http.get(url, (res: IncomingMessage) => {
    if(res.statusCode !== 200){
      callback(CallBackStatus.error, {msg: `${res.statusCode} 网络错误`})
      return
    }

    // 进度处理
    const len = parseInt(res.headers['content-length'] as string)  // 总长度bytes
    const total = (len / 1048576).toFixed(2)  // 总长度 Mb
    let cur = 0
    res.on("data", chunk => {
      cur += chunk.length
      const percent = (100.0 * cur / len).toFixed(2) // 当前进度百分比
      const current = (cur / 1048576).toFixed(2) // 当前进度Mb
      callback(CallBackStatus.progress, {percent, current, total})
    })

    // 结束处理
    res.on("end", () => {
      callback(CallBackStatus.finish)
    })

    // 错误处理
    res.on("error", err => {
      fs.rmSync(filePath)
      callback.bind(null, CallBackStatus.error, {msg: err.message})
    })

    res.pipe(file)
  })

  // req错误处理
  req.on("error", err => {
    fs.rmSync(filePath)
    callback.bind(null, CallBackStatus.error, {msg: err.message})
  })
}
